import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import Element from 'element-ui'
import axios from 'axios'
//加密插件
import CryptoJS from 'crypto-js/crypto-js'

import '../theme/index.css'
import '@assets/css/reset.styl'
import '@assets/css/index.styl'
import routes from './router/router.js'

Vue.use(VueRouter)
Vue.use(Element)
Vue.config.productionTip = false


const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
});

router.beforeEach((to, from, next) => {
  if (sessionStorage.getItem('token' && to.path !== '/login')) {
    next({
      path: '/login'
    })
  } else {
    next()
  }
})

//AES加密
function Encrypt(word) {
  let key = 'mendaomendao2020';
  let iv = '';

  key = CryptoJS.enc.Utf8.parse(key);
  iv = CryptoJS.enc.Utf8.parse(iv);

  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.ZeroPadding
  });
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

}

function Decrypt(word) {
  let key = 'mendaomendao2020';
  let iv = '';
  key = CryptoJS.enc.Utf8.parse(key);
  iv = CryptoJS.enc.Utf8.parse(iv);

  let base64 = CryptoJS.enc.Base64.parse(word);
  let src = CryptoJS.enc.Base64.stringify(base64);

  let decrypt = CryptoJS.AES.decrypt(src, key, {
    iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.ZeroPadding
  });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}


//设置axios为form-data
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = [function (data) {
  let ret = ''
  for (let it in data) {
    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  return ret
}];
Vue.prototype.axios = axios;

// axios 请求拦截
axios.interceptors.request.use(config => {
  if(!(config.url.indexOf('login') > -1)) {
    let token = sessionStorage.getItem('token');
    config.headers["token"] = token;
    // config.headers = {
    //   'Content-Type':'multipart/form-data'
    // };
    if(sessionStorage.getItem('userInfo')) {
      let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
      config.headers["userId"] = userInfo.id;
    }
  }
  // 加自己的业务逻辑
  return config
});

// axios 响应拦截
axios.interceptors.response.use(config => {
  // 加自己的业务逻辑
  let data = Decrypt(config.data);
  let dataStr = data.toString();
  let index = dataStr.lastIndexOf("}");
  dataStr = dataStr.substring(0, index + 1);
  config.data = JSON.parse(dataStr);
  // 判断登录是否失效，失效跳转登录提示用户登录
  if(config.data.code === 403) {
    // TODO 提示用户
    // this.$message.error("登录失效，请重新登录");
    sessionStorage.removeItem("token");
    sessionStorage.removeItem("userInfo");
    router.replace({path: '/login'})
  }

  return config;
});

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')
